import React, { useEffect, useState } from 'react'
import { Button, Table, Modal, Form, Input, DatePicker, Space } from 'antd'
import type { ColumnsType } from 'antd/es/table';
import { deleteList, addList } from '../../api';
import Filter from '../../components/xx-filter'
import axios from 'axios'
import { promisitionCB } from '../../utils/tool'
import Promisstion from '../../components/xx-promistion'
interface ListRawState {
  "id": string
  "title": string
  "image": string
  "time": string
  "desc": string
  "price": number
}

const Index: React.FC = () => {
  const [fitlerParams, setFilterParams] = useState({});
  // 1. 数据容器
  const [list, setList] = useState<ListRawState[]>([])
  // 2. 请求函数
  const getList = async () => {
    const res = await axios('/api/list', { params: fitlerParams })
    setList(res.data.data)
  }
  // 3. 副作用函数
  useEffect(() => {
    getList()
  }, [fitlerParams])
  // 4. 列数据
  const columns: ColumnsType<ListRawState> = [{
    key: 'id',
    title: 'ID',
    dataIndex: 'id',
  }, {
    key: 'title',
    title: '标题',
    dataIndex: 'title',
  }, {
    key: 'image',
    title: '图片',
    dataIndex: 'image',
    render: (text) => <img src={text} alt="图片" height="20" />
  }, {
    key: 'time',
    title: '时间',
    dataIndex: 'time',
    sorter: (a, b) => new Date(a.time).getTime() - new Date(b.time).getTime()
  }, {
    key: 'desc',
    title: '描述',
    dataIndex: 'desc',
  }, {
    key: 'price',
    title: '单价',
    dataIndex: 'price',
    sorter: (a, b) => a.price - b.price
  }, {
    key: 'type',
    title: '类型',
    dataIndex: 'type',
  }, {
    key: 'action',
    title: '操作',
    dataIndex: 'action',
    render: (text, record) => (
      <Space>
        <Promisstion>
          <Button
            type="primary"
            danger
            onClick={() => {
              handleDelete(record.id)
            }}>删除</Button>
        </Promisstion>
        <Button
          type="primary"
        >编辑</Button>
      </Space>
    ),
  }]
  // 5. 实现删除， 通过id删除， 接口/api/list
  const handleDelete = promisitionCB(async (id: string) => {
    // 二次确认
    Modal.confirm({
      title: '删除提示',
      content: '确定删除该记录吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const resp = await deleteList({ id });
        await getList();
      },
    })
  })
  // 6 弹框状态
  const [open, setOpen] = useState(false)
  // 7. 添加列表
  const handleOk = async () => {
    // 获取form表单值
    const resp = await addList(form.getFieldsValue());
    await getList();
    setOpen(false);
  }
  // 8. 表单实例
  const [form] = Form.useForm();
  // 9. 选中的 key|id 数据
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  return (
    <div>
      <Filter fetchFn={(data: any) => setFilterParams(data)}></Filter>
      <div>
        <Space style={{ marginBottom: 10 }}>
          <Button onClick={() => setOpen(true)}>添加</Button>
          <Button onClick={() => handleDelete(selectedRowKeys.join(","))} type="primary" danger disabled={selectedRowKeys.length === 0}>选中删除</Button>
        </Space>
      </div>

      {/* 使用 antd Table组件 渲染list数据 */}
      <Table<ListRawState>
        // 选中
        rowSelection={{
          onChange(selectedRowKeys: React.Key[]) {
            setSelectedRowKeys(selectedRowKeys)
          }
        }}
        // key => id
        rowKey={(record) => record.id}
        // 源数据
        dataSource={list}
        // 列数据
        columns={columns}
        // 分页参数
        pagination={{ pageSize: 10 }}
      >
      </Table>
      {/* 编辑/添加 */}
      <Modal
        onCancel={() => setOpen(false)}
        onOk={() => handleOk()}
        open={open} cancelText="取消" okText="确定" title="编辑">
        <Form
          form={form}
        >
          <Form.Item label="标题" name="title">
            <Input placeholder='请输入标题'></Input>
          </Form.Item>
          <Form.Item label="图片" name="image">
            <Input placeholder='请输入图片'></Input>
          </Form.Item>
          <Form.Item label="时间" name="time">
            {/* 时间选择器, 具体到 年月日 时分秒 */}
            <DatePicker format="YYYY-MM-DD HH:mm:ss" showTime></DatePicker>
          </Form.Item>
          <Form.Item label="描述" name="desc">
            <Input placeholder='请输入描述'></Input>
          </Form.Item>
          <Form.Item label="单价" name="price">
            <Input type="number" placeholder='请输入单价'></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>

  )
}

export default Index